//
//  TestRefreshViewViewController.m
//  TestRefreshView
//
//  Created by Jason Liu on 12-1-10.
//  Copyright 2012年 Yulong. All rights reserved.
//
#import "FMDBCollectionManager.h"
#import "FMDBSupplierManager.h"
#import "UserCollectionController.h"
#import "DetailShopViewController.h"
#import "PublicFunction.h"
#import "Collection.h"
#import "UICustomImageView.h"
@interface UserCollectionController (private)
- (void)refresh;
- (void)stopLoading;
- (void)startLoading;
@end
@implementation UserCollectionController
@synthesize collectionTableView;
@synthesize refreshView;

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"收藏";
    count = 0;//用来统计已经生成的店铺数量
    loadCount = 0;//用来统计载入的次数
    FMDBCollectionManager *fmdbCollectionManager = [[FMDBCollectionManager alloc] init];
    collectionArray = [fmdbCollectionManager getAllCollection];
    NSInteger collectionNum = [collectionArray count];
    if(collectionNum>=9){
        buttonNumber = 6;
    }
    else{
        buttonNumber = collectionNum-3;
    }
    [self refresh];
    [fmdbCollectionManager release];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 80;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    NSArray *nils = [[NSBundle mainBundle]loadNibNamed:@"RefreshView" owner:self options:nil];
    self.refreshView = [nils objectAtIndex:0];
    [refreshView setupWithOwner:tableView delegate:self];
    refreshView.isPullUp = YES;
    refreshView.hidden = YES;
    return refreshView;
}

- (void)viewDidUnload
{
    [self setRefreshView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [collectionTableView release];
    [refreshView release];
    [super dealloc];
}
// 停止，可以触发自己定义的停止方法
- (void)stopLoading {
    [collectionTableView reloadData];
    [refreshView stopLoading];
}
// 开始，可以触发自己定义的开始方法
- (void)startLoading {
    refreshView.hidden = NO;
    [refreshView startLoading];
    // 模拟2秒后停止
    buttonNumber=buttonNumber+3;
    if(loadCount != 0){
        count = 0;
        [self performSelector:@selector(stopLoading) withObject:nil afterDelay:2];
    }
    loadCount++;
}
// 刷新
- (void)refresh {
    [self startLoading];
}
#pragma mark - RefreshViewDelegate
- (void)refreshViewDidCallBack {
    [self refresh];
}
#pragma mark - UIScrollView 
// 刚拖动的时候
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [refreshView scrollViewWillBeginDragging:scrollView];
}
// 拖动过程中
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [refreshView scrollViewDidScroll:scrollView];
}
// 拖动结束后
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [refreshView scrollViewDidEndDragging:scrollView willDecelerate:decelerate];
}

#pragma mark - Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return buttonNumber/3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FMDBCollectionManager *fmdbCollectionManager = [[FMDBCollectionManager alloc] init];
    collectionArray = [fmdbCollectionManager getAllCollection];
    static NSString *identifier=@"identifier";
    UITableViewCell *cell=[tv dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
    }
    for (UIView *view in [cell subviews]) {
        [view removeFromSuperview];
    }
    for ( int i =0 ;i<3 ;i++ ) {
        if(count == [collectionArray count]){
            return cell;
        }
        Collection *collection = [collectionArray objectAtIndex:count];
        //图片
        UICustomImageView *supplierImg=[[UICustomImageView alloc] initWithFrame:CGRectMake(10+100*i ,10,90, 90)];
        UIButton *imgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        imgBtn.frame=CGRectMake(10+100*i ,10,90, 90);
        [imgBtn setTag:collection.supplierId];
        imgBtn.backgroundColor = [UIColor clearColor];
        [imgBtn addTarget:self action:@selector(showDetailShop:) forControlEvents:UIControlEventTouchUpInside];
        
        //有商铺图片
        [supplierImg setContentMode:UIViewContentModeScaleAspectFit];
        [supplierImg setUserInteractionEnabled:YES];
        [supplierImg setImage:nil];
        [supplierImg setImageURL:collection.imgUrl];
        
        //名称背景
        UIButton *supplierNameBg=[UIButton buttonWithType:UIButtonTypeCustom];
        supplierNameBg.frame=CGRectMake(28+100*i,100, 54, 15);
        [supplierNameBg setBackgroundImage:[UIImage imageNamed:@"010.png"] forState:UIControlStateNormal];
        [supplierNameBg setTag:collection.supplierId];
        [supplierNameBg addTarget:self action:@selector(showDetailShop:) forControlEvents:UIControlEventTouchUpInside];
        [supplierNameBg setTitle:collection.supplierName forState:UIControlStateNormal];
        supplierNameBg.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:12]; 
        [cell addSubview:supplierImg];
        [cell addSubview:imgBtn];
        [cell addSubview:supplierNameBg];
        [supplierImg release];
        count++;
    }
    return cell;
}
-(void)showDetailShop:(id)sender{
    NSString *supplierId = [NSString stringWithFormat:@"%d",[sender tag]];
    Supplier *supplierDetail;
    fmdbSupplierManager=[[FMDBSupplierManager alloc]init];
    supplierDetail=[fmdbSupplierManager getSupplierDetailByIdFromLoc:supplierId];
    [fmdbSupplierManager release];
    //创建新的试图并将试图推入栈中
    DetailShopViewController *detailShopViewController = [[DetailShopViewController alloc]initWithNibName:@"DetailShopViewController" bundle:nil];
    UINavigationController  *theNavController = [[UINavigationController alloc]
                                                 initWithRootViewController:detailShopViewController];
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity :2];
    [dictionary setObject:supplierId forKey:@"supId"];
    [dictionary setObject:supplierDetail forKey:@"Supplier"];
    [detailShopViewController setRecieveDictionary:dictionary];
    [detailShopViewController release];
    theNavController.navigationBar.tintColor = [UIColor blackColor];
    [self.navigationController pushViewController: detailShopViewController animated:YES];
    [theNavController release];
}
@end
